package org.qhhc.thread.threadlocals;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalStudy {
    // 使用 ThreadLocal 包装 SimpleDateFormat
    private static final ThreadLocal<SimpleDateFormat> dateFormatHolder =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static String formatDate(Date date) {
        return dateFormatHolder.get().format(date); // 每个线程获取自己的实例
    }

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                try {
                    // 使用线程安全的日期格式化
                    System.out.println(Thread.currentThread().getName() + ": "
                            + formatDate(new Date()));
                } finally {
                    dateFormatHolder.remove(); // 清理 ThreadLocal 防止内存泄漏[3,5](@ref)
                }
            });
        }
        executor.shutdown();
    }
}